package com.company.lagou.homework.homework3;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class CopyTest {
    static File copyFromFile = new File("D:\\code\\testCopyFrom");
    static File copyToFile = new File("D:\\code\\testCopyTo");

    public static void main(String[] args) {
        System.out.println("拷贝开始.....");
        copy(copyFromFile,copyToFile);
        System.out.println("拷贝结束！");
    }

    private static void copy(File copyFromFile, File copyToFile) {
        File[] files = copyFromFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            //创建输出文件的全路径名
            File fileTo = new File(copyToFile, file.getName());
            if (file.isFile()) {
                //执行拷贝
                try {
                    //读取输入流
                    FileInputStream fis = new FileInputStream(file);
                    //创建输出流
                    //目标文件夹创建
                    if (!copyToFile.exists()) {
                        copyToFile.mkdirs();
                    }
                    //创建输出文件的全路径名
                    FileOutputStream fos = new FileOutputStream(fileTo);
                    //执行拷贝
                    byte[] bytes = new byte[1024*8];
                    int len = 0;
                    while ((len = fis.read(bytes))!=-1){
                        fos.write(bytes,0,len);
                    }
                    fos.close();
                    fis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                //递归
                copy(file,fileTo);
            }
        }

    }



}
